package com.cmccgz.baselibrary.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.cmccgz.baselibrary.R;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.orhanobut.logger.Logger;


/**
 * @author: Huang
 * @Descripion:
 * @date 2017/5/25 11:07
 */

public abstract class BaseFragment extends Fragment {

    protected Activity mContext;
    protected ProgressDialog progressDialog;
    protected AlertDialog alertDialog;
    protected View root;
    protected Handler handler = new Handler();
    protected boolean needsInit;
    protected boolean isSaveInstance;
    private Bundle savedInstanceState;
    protected boolean isShowTimeLog =false;
    protected AlertDialog tipsDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isSaveInstance = savedInstanceState != null;
        this.savedInstanceState = savedInstanceState;
        showTimeLog("onCreate");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (needsInit = root == null) {
            root = inflater.inflate(setLayoutId(), container, false);
        }
        showTimeLog("onCreateView,root="+root);

        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (needsInit) {
            initView();
        }
        showTimeLog("onViewCreated,needsInit="+needsInit);
    }

    @Override
    public void onDestroyView() {
        showTimeLog("onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        showTimeLog("onDestroy");
        super.onDestroy();
    }

    protected abstract int setLayoutId();

    protected abstract void initView();

    protected View findViewById(int id) {
        try {
            return root.findViewById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void showToast(String message) {
        ToastUtils.show(mContext, message);
    }

    protected void showToast(@StringRes int stringId) {
        ToastUtils.show(mContext, stringId);
    }


    protected void showLoadingDialog(String message) {
        try {
            progressDialog = ProgressDialog.show(mContext, "", message, false, true);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    protected void showLoadingDialog(String message, DialogInterface.OnCancelListener cancelListener) {
        try {
            progressDialog = ProgressDialog.show(mContext, "", message, false, true, cancelListener);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    protected void dismissLoadingDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    protected void dismissLoadingDialog(String msg) {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
                showToast(msg);
            }
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    protected void showConfirmDialog(String title, String message, String okText, DialogInterface.OnClickListener onOkClickListener, String cancleText, DialogInterface.OnClickListener onCancleClickListener) {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(title).setMessage(message).setPositiveButton(okText, onOkClickListener).setNegativeButton(cancleText, onCancleClickListener);
            alertDialog = builder.create();
            alertDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }
    protected void showTipsDialog(String title, String message, String okText, DialogInterface.OnClickListener onOkClickListener) {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(title).setMessage(message).setPositiveButton(okText, onOkClickListener);
            tipsDialog = builder.create();
            tipsDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }
    /**
     * 设置点击间隔
     *
     * @param v
     * @param spanMis
     */
    protected void setClickSpan(final View v, long spanMis) {
        v.setClickable(false);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                v.setClickable(true);
            }
        }, spanMis);
    }

    @Override
    public void startActivity(Intent intent) {
        startActivity(intent,true);
    }

    public void startActivity(Intent intent,boolean isAnim) {
        super.startActivity(intent);
        if (isAnim)
            mContext.overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        startActivityForResult(intent,requestCode,true);
    }

    public void startActivityForResult(Intent intent, int requestCode,boolean isAnim) {
        super.startActivityForResult(intent, requestCode);
        if (isAnim)
            mContext.overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
    }
    /**
     * 隐藏软键盘
     *
     * @param v
     */
    protected void hideSoftKeyboard(View v) {
        try {
            InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 强制隐藏软键盘
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (root != null) {
            hideSoftKeyboard(root);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        needsInit=true;
        isSaveInstance=true;
        showTimeLog("onSaveInstanceState");
        super.onSaveInstanceState(outState);
    }

    public Bundle getSavedInstanceState() {
        return savedInstanceState;
    }

    private void showTimeLog(String msg){
        if (isShowTimeLog) {
            Logger.i(getClass().getSimpleName()+"---="+msg);
        }
    }
}
